package com.jasonzhou.onetomanycontrol.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.viewbinding.ViewBinding
import com.jasonzhou.onetomanycontrol.R
import com.jasonzhou.onetomanycontrol.constant.MessageConstant
import com.jasonzhou.onetomanycontrol.util.AppLanguageUtils
import com.jasonzhou.onetomanycontrol.util.StatusBarUtil

open abstract class BaseActivity<T : ViewBinding> : AppCompatActivity() {

    private var mExitTimer: Long = 0
    protected var isOpenKeyListener = false

    protected var lastRecordSendTime: Long = 0L

    protected abstract fun getViewBinging(): T
    protected lateinit var binding: T

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.immersive(this)
        binding = getViewBinging()
        setContentView(binding.root)
    }

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(
            AppLanguageUtils.attachBaseContext(
                newBase,
                AppContent.instance.getString(MessageConstant.KEY_LANGUAGE_VALUE, MessageConstant.AUTO)
            )
        )

    }


    fun getBaseColor(resId: Int) = ContextCompat.getColor(this, resId)


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                if (isOpenKeyListener) {
                    if (System.currentTimeMillis() - mExitTimer > 2000) {
                        AppContent.instance.toast.show(R.string.back_btn_tips, 100, Gravity.CENTER)
                        mExitTimer = System.currentTimeMillis()
                    } else {
                        val intent = Intent()
                        intent.action = Intent.ACTION_MAIN
                        intent.addCategory(Intent.CATEGORY_HOME)
                        startActivity(intent)
                        finish()
                    }
                } else {
                    this.finish()
                    overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right)
                }
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }
}